<template>
  <div class="root">

    <div class="container-chat">
      <div class="header">
      <span
          class="tab ai"
          :class="{
          'selected': selectedTab === 0
        }"
          @click="selectedTab = 0">
        医疗智能对话
      </span>
        <span class="tab" :class="{ 'selected': selectedTab === 1  }" @click="selectedTab = 1">
        智能搜索
      </span>
        <el-button class="clearStorage" @click="clearCache">清空缓存</el-button>
      </div>

      <div id="chatContent" v-if="selectedTab===0" class="chat-content" ref="chatContent">
        <div class="q-a" v-for="(item, index) in questionList" :key="index">
          <div class="question-box" v-if="item.question">
            <p class="question-content">
              {{ item.question }}
            </p>
          </div>
          <div v-if="item.answer">
            <div class="answer">
              <div class="avatar"></div>
              <div class="answer-content">
                <dl class="answer-text" >
                  {{ item.answer.text }}
                  <div v-for="(button, index) in item.answer.buttons" :key="index">
                    <div @click="sendButtonReq(button.payload,button.title)">
                      <el-button class="answer-btn" size="small" round >
                        {{ button.title }}
                      </el-button>
                    </div>
                  </div>
                </dl>
                <dl class="answer-text" v-html="item.answer.video">
                  <!--{{ item.answer.text }}-->
                </dl>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="selectedTab===1" class="chat-content" ref="chatContent">
        <div class="q-a" v-for="(item, index) in questionList2" :key="index">
          <div class="question-box" v-if="item.question">
            <p class="question-content">
              {{ item.question }}
            </p>
          </div>
          <div v-if="item.answer">
            <div class="answer">
              <div class="avatar"></div>
              <div class="answer-content">
                <dl class="answer-text">
                  {{ item.answer.overview }}
                  <div v-for="(relative, index) in item.answer.relat" :key="index">
                    <div @click="sendButtonReq2(relative)">
                      <el-button class="answer-btn" size="small" round v-html="relative">
                      </el-button>
                    </div>
                  </div>
                </dl>
              </div>
            </div>
            <div v-if="item.answer">
              <feedback
                  v-show="!feedBackList.includes(index)"
                  @on-like="onLike(index)"
                  @on-dislike="onDislike(index)"/>
            </div>
            <div class="feedback" v-show="feedBackList.includes(index)">
              谢谢您的反馈
            </div>
          </div>
        </div>
      </div>
      <div v-if="selectedTab === 0" class="input-box">
        <input
            id="inputOne"
            type="text"
            placeholder="请输入问题内容，我来为你解答…"
            :value="input"
            @input="onChangeInput"
            ref="input"
            @keyup.enter="sendQuestion">
        <div class="send" @click="sendQuestion"></div>
      </div>

      <div v-if="selectedTab === 1" class="input-box">
        <input
            type="text"
            placeholder="请输入问题内容，我来为你解答…"
            :value="input"
            @input="onChangeInput"
            ref="input"
            @keyup.enter="sendQuestion2">
        <div class="send" @click="sendQuestion2"></div>
      </div>
    </div>
    <hot-topic class="hot-topic" v-show="showHot"/>
  </div>

</template>

<script>
import eventBus from '../../common/eventBus.js'
import AdviceBox from './AdviceBox'
import Feedback from './Feedback'
import contralShink from './ContralShink'
import BigImg from '../../common/BigImg.vue'
import HotTopic from './HotTopic'
import {Loading} from "element-ui";
import {getUserInfo} from "@/utils/userInfo";
import axios from "axios";
import $ from 'jquery'
export default {
  name:'Chat',
  meta: {
    keepAlive: true,
  },
  data() {
    return {
      count: 89,
      input: '',
      showImg: false,
      imgSrc: '',
      imgPre: '',
      msgid: '',
      imgArr: [],
      imgPreArr: [],
      selectedTab: 0,
      result: '',
      questionList: [{}],
      questionList2: [{}],
      feedBackList: [],
      word: '',
      responseResult: '',
      dislikeIndex: 0,
      showHot: true,
      hasLiked: false,
      showAdvice: false,
      likeIcon: require('../../../public/picture/like.png'),
      likedIcon: require('../../../public/picture/liked.png'),
      winWidth: window.innerWidth,
      winHeight: window.innerHeight,
      ans: '',
      sender: '8',
      message:''
    }
  },
  components: {
    // eslint-disable-next-line vue/no-unused-components
    'big-img': BigImg,
    // eslint-disable-next-line vue/no-unused-components
    AdviceBox,
    // eslint-disable-next-line vue/no-unused-components
    Feedback,
    // eslint-disable-next-line vue/no-unused-components
    contralShink,
    // eslint-disable-next-line vue/no-unused-components
    HotTopic

  },
  beforeUpdate() {
    let userInfo = JSON.parse(getUserInfo())
    this.sender = userInfo.uid
  },
  mounted() {
    let loading = Loading.service({fullscreen: true});
    let userInfo = JSON.parse(getUserInfo())
    this.sender = userInfo.uid
    //获取热门问答消息
    this.getEventDatas()
    loading.close()
  },
  activated() {
    // 组件被激活时从缓存中加载数据
    this.questionList = JSON.parse(localStorage.getItem('questionList'))
    this.questionList2 = JSON.parse(localStorage.getItem('questionList2'))
  },
  deactivated() {
    // 组件被停用时保存数据到缓存
    if (this.questionList === null){
      localStorage.setItem('questionList', JSON.stringify([]))
    }else {
      let questionList = JSON.stringify(this.questionList);
      localStorage.setItem('questionList', questionList)
    }
    if (this.questionList2 === null){
      localStorage.setItem('questionList2', JSON.stringify([]))
    }else {
      let questionList2 = JSON.stringify(this.questionList2);
      localStorage.setItem('questionList2', questionList2)
    }
  },
   methods: {
     async generateResponse(content) {
      const url = 'https://api.openai.com/v1/chat/completions';
      const data = {
        model: "gpt-3.5-turbo",
        messages: [
          {
            role: "user",
            content: content
          }
        ],
        "temperature": 0.7
      };
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer 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',
      };
      let response = await axios.post(url, data, { headers: headers });
      return  response.data.choices[0].message.content;
    },
     clearCache() {
       localStorage.setItem("questionList",JSON.stringify([])); // 清空缓存数据
       localStorage.setItem("questionList2",JSON.stringify([])); // 清空缓存数据
       location.reload(); // 刷新页面
     },
    getEventDatas() {
      const that = this
      eventBus.$on('hotTopic', function (val, ans) {
        that.word = val
        that.ans = ans
        that.questionList.push({question: that.word})
        setTimeout(() => {
          that.$refs.chatContent.scrollTop = 99999
        }, 50)
        const message = that.word
        const sender = that.sender
        const loadAns = {text:'整理回答中，请等待。。。'}
        that.questionList.push({answer: loadAns})
        that.$store.dispatch('rasaChat', {sender, message}).then((res) => {
          //删除等待标识
          that.questionList.pop()
          // 循环存入返回值，多个text回复
          for (let i = 0; i < res.RasaResponse.length; i++) {
            let answer1 = res.RasaResponse[i];
            let attachment = answer1.attachment
            //存在实体
            if (attachment !== 'false'){
              //增加热度
              that.$store.dispatch('addHot', {attachment}).then((res) => {
                console.log("增加热度成功")
              })
            }

            if ( answer1.text.length > 0) {
              that.questionList.push({answer: answer1})
            }
          }
          // that.word=''
          setTimeout(() => {
            that.$refs.chatContent.scrollTop = 99999
          }, 50)
        })
      })
    },
    onChangeInput(e) {
      this.input = e.target.value
      this.$refs.input.value = e.target.value
      this.count = 89 - this.input.length
    },
    sendQuestion() {
      let inputOne =  $("#inputOne")
      inputOne.attr("readOnly","readOnly")
      this.getList()

    },
    sendQuestion2() {
      this.getList2()
    },
    sendButtonReq(payload, title) {
      let inputOne =  $("#inputOne")
      this.questionList.push({question: title})
      setTimeout(() => {
        this.$refs.chatContent.scrollTop = 99999
      }, 50)
      const message = payload
      const sender = this.sender
      this.input = ''
      const loadAns = {text:'整理回答中，请等待。。。'}
      inputOne.attr("readOnly","readOnly")
      this.questionList.push({answer: loadAns})
      this.$store.dispatch('rasaChat', {sender, message}).then((res) => {
        this.questionList.pop()
        inputOne.removeAttr("readOnly")
        // 循环存入返回值，多个text回复
        for (let i = 0; i < res.RasaResponse.length; i++) {
          let answer1 = res.RasaResponse[i];
          let attachment = answer1.attachment
          //存在实体
          if (attachment){
            //rasa没有数据时
            if (attachment === 'false'){
              this.questionList.push({answer: loadAns})
              inputOne.attr("readOnly","readOnly")
              let that = this
              that.generateResponse(message).then((gptRes)=>{
                that.questionList.pop()
                inputOne.removeAttr("readOnly")
                //封装answer
                let recipient_id = that.sender
                let text = gptRes
                let answer = {recipient_id,text}
                that.questionList.push({answer: answer})
                //获取最新的message的id
                let mid = res.mid
                //更新response
                let response = text
                that.$store.dispatch('updateMessageInfo', {mid, response}).then(()=>{
                })
              })
            }else {
              let recipient_id = this.sender
              let video = `<a style="color: #0082ba" href="/#/videoList?disease=${attachment}">点击此处可查看<strong style="font-weight: bold;" class="videoEntity">${attachment}</strong>相关视频</a>`
              let answer = {recipient_id,video}
              this.questionList.push({answer:answer})
              //增加热度
              this.$store.dispatch('addHot', {attachment}).then((res) => {
                console.log("增加热度成功")
              })
            }
            break
          }

          if (answer1.text.length > 0 && !answer1.text.includes("暂无")) {
            this.questionList.push({answer: answer1})
          }
        }
        setTimeout(() => {
          this.$refs.chatContent.scrollTop = 99999
        }, 50)
      })
    },
    sendButtonReq2(relative) {
      this.questionList2.push({question: relative})
      setTimeout(() => {
        this.$refs.chatContent.scrollTop = 99999
      }, 50)
      const keyword = relative
      const sender = this.sender
      this.input = ''
      const loadAns = {overview:'整理回答中，请等待。。。'}
      this.questionList2.push({answer: loadAns})
      this.$store.dispatch('ChatAI', {sender, keyword}).then((res) => {
        this.questionList2.pop()
        // 循环存入返回值，多个text回复
        let answer1 = res.data
        this.questionList2.push({answer: answer1})
        this.word = ''
        this.input = ''
        setTimeout(() => {
          this.$refs.chatContent.scrollTop = 99999
        }, 50)
      })
    },
    getList: function () {
      let inputOne =  $("#inputOne")
      if (this.input.length === 0) {
        alert("不可以输入空消息")
        return false;
      }
      this.questionList.push({question: this.input})
      setTimeout(() => {
        this.$refs.chatContent.scrollTop = 99999
      }, 50)
      this.word = this.input
      const message = this.word
      const sender = this.sender
      this.input = ''
      const loadAns = {text:'整理回答中，请等待。。。'}
      this.questionList.push({answer: loadAns})
      this.$store.dispatch('rasaChat', {sender, message}).then((res) => {
        this.questionList.pop()
        inputOne.removeAttr("readOnly")
        // 循环存入返回值，多个text回复
        for (let i = 0; i < res.RasaResponse.length; i++) {
          let answer1 = res.RasaResponse[i];
          let attachment = answer1.attachment
          //存在实体,最后一层
          if (attachment){
            if (attachment === 'false'){
              this.questionList.push({answer: loadAns})
              inputOne.attr("readOnly","readOnly")
              let that = this
              that.generateResponse(message).then((gptRes)=>{
                that.questionList.pop()
                inputOne.removeAttr("readOnly")
                //封装answer
                let recipient_id = that.sender
                let text = gptRes
                let answer = {recipient_id,text}
                that.questionList.push({answer: answer})
                //获取最新的message的id
                let mid = res.mid
                //更新response
                let response = text
                that.$store.dispatch('updateMessageInfo', {mid, response}).then(()=>{
                  console.log("更新message成功")
                })
              })
            }else {
              let recipient_id = this.sender
              let video = `<a style="color: #0082ba" href="/#/videoList?disease=${attachment}">点击此处可查看<strong style="font-weight: bold;" class="videoEntity">${attachment}</strong>相关视频</a>`
              let answer = {recipient_id,video}
              this.questionList.push({answer:answer})
              // console.log(attachment)
              //增加热度
              this.$store.dispatch('addHot', {attachment}).then((res) => {
                console.log("增加热度成功")
              })
            }
            break
          }
          if (answer1.text.length > 0 && !answer1.text.includes("暂无")) {
            this.questionList.push({answer: answer1})
          }
        }
        this.word = ''
        this.input = ''
        setTimeout(() => {
          this.$refs.chatContent.scrollTop = 99999
        }, 50)
      })

    },
    getList2: function () {
      if (this.input.length === 0) {
        alert("不可以输入空消息")
        return false;
      }
      this.questionList2.push({question: this.input})
      setTimeout(() => {
        this.$refs.chatContent.scrollTop = 99999
      }, 50)
      this.word = this.input
      const keyword = this.word
      const sender = this.sender
      this.input = ''
      const loadAns = {overview:'整理回答中，请等待。。。'}
      this.questionList2.push({answer: loadAns})
      this.$store.dispatch('ChatAI', {sender, keyword}).then((res) => {
        this.questionList2.pop()
        // 循环存入返回值，多个text回复
        let answer1 = res.data
        this.questionList2.push({answer: answer1})
        this.word = ''
        this.input = ''
        setTimeout(() => {
          this.$refs.chatContent.scrollTop = 99999
        }, 50)
      })
    }
  }
}
</script>

<style scoped>
.root {
  width: 924px; /*no*/
  height: 684px; /*no*/
  box-sizing: border-box;
  overflow: hidden;
  border-radius: 6px;
  background-color: #ffffff;
  position: relative;
  padding-right: 256px; /*no*/
  margin: 20px auto 0;
  border: 2px solid #e2effc;


}

.container-chat {
  width: 100%;
  height: 100%;
  position: relative;


}

.hot-topic {
  /*padding-right: 256px;!*no*!*/
  position: absolute;
  width: 256px;
  left: 666px;
}

.header {
  height: 57px; /*no*/
  text-align: left;
  padding-left: 30px;
  box-sizing: border-box;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 1px 0 0 #F5F5F5;
  z-index: 99;
}

.tab {
  display: inline-block;
  line-height: 57px; /*no*/
  color: #9A9A9F;
  font-size: 16px; /*no*/
  position: relative;
  cursor: pointer;
}

.selected {
  font-weight: bold;
  color: #1F1F1F;
}

.tab.ai {
  margin-right: 23px;
}

.chat-content {
  padding-top: 44px;
  /*padding-bottom: 140px;!*no*!*/
  /*height: 613px;*/
  overflow-y: scroll;
  box-sizing: border-box;
  position: absolute;
  top: 0;
  bottom: 100px; /*no*/
  width: 100%;
  left: 0;
}

.expand {
  position: absolute;
  right: 20px; /*no*/
  top: 50%;
  transform: translateY(-50%);
  width: 20px; /*no*/
  cursor: pointer;
  z-index: 99;
}

.expanded {
  /*反转*/
  transform: translateY(-50%) rotate(180deg);
}

.avatar {
  width: 33px; /*no*/
  height: 33px; /*no*/
  border-radius: 33px;
  background-color: #419dbf;
  background-image: url('../../../public/picture/bot.png');
  background-size: 20px; /*no*/
  background-position: center;
  background-repeat: no-repeat;
  margin-left: 16px;
  position: absolute;
}

.time {
  text-align: left;
  margin-top: 16px;
}

.time span {
  display: inline-block;
  color: #fff;
  font-size: 12px; /*no*/
  padding: 3px 7px;
  background: #E3E3E3;
  border-radius: 100px;
}

.question-box {
  text-align: right;
  margin-top: 24px; /*no*/
  margin-right: 28px;
  margin-left: 50px;
}

.question-content {
  display: inline-block;
  position: relative;
  text-align: left;
  background-color: #419dbf;
  padding: 19px; /*no*/
  color: #fff;
  font-size: 15px; /*no*/
  border-radius: 10px; /*no*/
}

.answer {
  position: relative;
  margin-top: 28px; /*no*/
}

.more {
  text-align: left;
  color: #419dbf;
  font-size: 12px; /*no*/
}

.answer-content {
  display: inline-block;
  background-color: #fff;
  padding: 13px 19px 11px 25px;
  box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.10);
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
  font-size: 10px;
  margin-left: 70px; /*no*/
  margin-right: 76px; /*no*/
  position: relative;
  white-space: pre-line;
}

.answer-content::before {
  content: '';
  position: absolute;
  left: -8px;
  top: 0;
  width: 0;
  height: 0;
  border-top: 20px solid #fff;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.answer-content dl {
  font-size: 15px;
  line-height: 25px;
}

.answer-content h1 {
  color: #252526;
  font-size: 13px; /*no*/
}

.answer-content h1 span {
  color: #419dbf;
}

.answer-content h2 {
  color: #252526;
  font-size: 13px; /*no*/
  margin-top: 21px;
}

.answer-content li {
  margin: 8px 0; /*no*/
  font-size: 13px; /*no*/
  line-height: 20px; /*no*/
  color: #252526;
}

.answer-content .tag {
  font-size: 18px; /*no*/
  line-height: 15px; /*no*/
  display: inline-block;
  padding: 0 8px;
  border-radius: 3px;
  color: #fff;
}

.tag1 {
  background-color: #FCB474;
}

.tag2 {
  background-color: #97C0FC;
}

.feedback {
  margin-top: 17px; /*no*/
  color: #9a9a9f;
  font-size: 12px; /*no*/
  line-height: 17px; /*no*/
  text-align: left;
  padding-left: 80px;
}

.feedback img {
  width: 22px; /*no*/
  margin-left: 21px;
  cursor: pointer;
}

.dislike {
  transform: rotate(180deg);
}

.input-box {
  position: absolute;
  bottom: 15px;
  left: 12px;
  right: 18px;
  /*height: 58px;*/
  border-radius: 99px;
  background-color: #fff;
  border: 1px solid #D6D6D6;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.10);
  padding: 9px 19px; /*no*/
  display: flex;
  align-items: center;
  z-index: 999;
}

.input-box input {
  flex: 1;
  padding-right: 30px;
  font-size: 14px; /*no*/
  outline: none;
  border: none;
  height: 39px; /*no*/
  line-height: 39px; /*no*/
}

.input-box input::-webkit-input-placeholder {
  color: #D2D2D6;
}

.addPicturePc {
  width: 39px; /*no*/
  height: 39px; /*no*/
  border-radius: 99px;
  background-color: #419dbf;
  background-image: url('../../../public/picture/pluse.png');
  background-size: 50%;
  background-repeat: no-repeat;
  background-position: center;
}

.addPicturePc input {
  width: 38px;
  height: 38px;
  z-index: 99;
  opacity: 0.01;
}

.send {
  width: 39px; /*no*/
  height: 39px; /*no*/
  border-radius: 99px;
  background-color: #419dbf;
  background-image: url('../../../public/picture/ss.png');
  background-size: 50%;
  background-repeat: no-repeat;
  background-position: center;
}

.upload {
  width: 39px; /*no*/
  height: 39px; /*no*/
  border-radius: 99px;
  background-color: #419dbf;
  background-image: url('../../../public/picture/pluse.png');
  background-size: 50%;
  background-repeat: no-repeat;
  background-position: center;
}

.count {
  display: inline-block;
  position: absolute;
  font-size: 12px; /*no*/
  color: #9a9a9f;
  bottom: 50%;
  transform: translateY(50%);
  right: 74px;
}
.answer-btn{
  margin-top: 5px;
}

.answer-btn:focus{
  background-color: rgba(69, 162, 196, 0.99);
  color: white;
  border-color: rgba(65, 157, 191, 0.99);
}
.answer-btn:hover{
  background-color: rgba(69, 162, 196, 0.99);
  color: white;
  border-color: rgba(65, 157, 191, 0.99);
}
.clearStorage {
  float: right;
  margin: 10px;
  border-color: rgba(65, 157, 191, 0.99);
}
.clearStorage:focus{
  background-color: rgba(69, 162, 196, 0.99);
  color: white;
  border-color: rgba(65, 157, 191, 0.99);
}
.clearStorage:hover{
  background-color: rgba(69, 162, 196, 0.99);
  color: white;
  border-color: rgba(65, 157, 191, 0.99);
}

</style>
